package com.qf.fmall2202.shopcart.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2202.product.entity.Product;
import com.qf.fmall2202.product.entity.ProductImg;
import com.qf.fmall2202.product.entity.ProductSku;
import com.qf.fmall2202.product.service.IProductImgService;
import com.qf.fmall2202.product.service.IProductService;
import com.qf.fmall2202.product.service.IProductSkuService;
import com.qf.fmall2202.shopcart.entity.ShoppingCart;
import com.qf.fmall2202.shopcart.service.IShoppingCartService;
import com.qf.fmall2202.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车  前端控制器
 * </p>
 *
 * @author lzh
 * @since 2022-11-08
 */
@CrossOrigin
@RestController
@RequestMapping("/shopcart")
public class ShoppingCartController {

    @Autowired
    IShoppingCartService shoppingCartService;
    /**定义一个vo收参
     * 请求体参数
     * {"cartNum":1,"productId":"3","productPrice":1,"skuId":"1",
     * "skuProps":"口味:原味;包装:盒装;","userId":"15"}
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){

//        //根据接收的数据存入数据库---》shoppoingCart表
//       shoppingCartService.addShopping(cartVo);
        //设置保存时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = simpleDateFormat.format(date);
        shoppingCart.setCartTime(dateStr);
        shoppingCartService.save(shoppingCart);
        return R.ok();

    }

    @GetMapping("list")
    public R list(Integer userId){

        List<ShoppingCart> shopcartList = shoppingCartService.listByUserId(userId);

        return R.ok().put("data",shopcartList);


    }




    @PutMapping("/update/{cartId}/{cartNum}")
    public R update(@PathVariable("cartId") Integer cartId,@PathVariable("cartNum")  String cartNum){

        //根据页面传过来的商品编号cartid查询整行信息
        ShoppingCart shoppingCart = shoppingCartService.getOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getCartId, cartId));
        //更改 cartNum
        shoppingCart.setCartNum(cartNum);
        //更改价格
//        shoppingCart.setProductPrice(new BigDecimal(cartNum).multiply(new BigDecimal(shoppingCart.getOriginalPrice())));

        //更改数据
        shoppingCartService.update(shoppingCart,new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getCartId, cartId));

        return R.ok();
    }

    @GetMapping("/listbycids")
    public R listByCids(String cids){

        List<ShoppingCart> cartList = shoppingCartService.listCids(cids);


        return R.ok().put("data",cartList);
    }


}
